#coding:utf8
from rest_framework import serializers
from .models import User
import re
from django_redis import get_redis_connection
from django.core.mail import send_mail
from django.conf import settings
from celery_tasks.email.tasks import send_active_email
from .models import Address


class RegisterCreateSerializer(serializers.ModelSerializer):

    password2 = serializers.CharField(label='二次密码',write_only=True)
    sms_code = serializers.CharField(label='短信验证码',max_length=6,min_length=6,write_only=True)
    allow = serializers.CharField(label='是否允许协议',write_only=True)

    #增加token
    token = serializers.CharField(label='token',read_only=True)

    class Meta:
        model = User
        fields = ['id','username','password','password2','mobile','sms_code','allow','token']
        extra_kwargs = {
            'id': {'read_only': True},
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

        # 进行校验
        # 单个字段的校验有 手机号码,是否同意协议
        def validate_mobile(self, value):
            if not re.match(r'1[345789]\d{9}', value):
                raise serializers.ValidationError('手机号格式不正确')
            return value

        def validate_allow(self, value):
            # 注意,前段提交的是否同意,我们已经转换为字符串
            if value != 'true':
                raise serializers.ValidationError('您未同意协议')
            return value
        # 多字段校验, 密码是否一致, 短信是否一致
        def validate(self, attrs):

            # 比较密码
            password = attrs['password']
            password2 = attrs['password2']

            if password != password2:
                raise serializers.ValidationError('密码不一致')
            # 比较手机验证码
            # 获取用户提交的验证码
            code = attrs['sms_code']
            # 获取redis中的验证码
            redis_conn = get_redis_connection('code')
            # 获取手机号码
            mobile = attrs['mobile']
            redis_code = redis_conn.get('sms_%s' % mobile)
            if redis_code is None:
                raise serializers.ValidationError('验证码过期')
            #注意 redis的数据是 bytes类型
            if redis_code.decode() != code:
                raise serializers.ValidationError('验证码不正确')

            return attrs


    def create(self, validated_data):

        # 删除多余字段
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        user = super().create(validated_data)
        # 修改密码
        user.set_password(validated_data['password'])
        user.save()

        #生成token
        from rest_framework_jwt.settings import api_settings

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        #eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjozLCJlbWFpbCI6IiIsImV4cCI6MTUzMDA2NDAxNiwidXNlcm5hbWUiOiJxaXJ1aWh1YSJ9.KTnwz3tVf-iKpPO25I6_Dbe8XU9y0ppX-mWiz-fkwBA
        user.token = token

        return user


class UserInfoSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


class EmailSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('id', 'email')
        extra_kwargs = {
            'email': {
                'required': True
            }
        }


    def update(self, instance, validated_data):

        #更新用户 邮箱字段
        to_email = validated_data.get('email')
        instance.email = to_email
        instance.save()

        #生成激活url
        verify_url = instance.generate_verify_email_url()

        #发送激活邮件
        # subject = "美多商城邮箱验证"
        # message = ''
        # from_email = settings.EMAIL_FROM
        # recipient_list = [to_email]
        # html_message = '<p>尊敬的用户您好！</p>' \
        #                '<p>感谢您使用美多商城。</p>' \
        #                '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
        #                '<p><a href="%s">%s<a></p>' % (to_email, verify_url, verify_url)
        # send_mail(subject,message,from_email,recipient_list,html_message=html_message)

        send_active_email.delay(to_email,verify_url)

        return instance


class AddressSerializer(serializers.ModelSerializer):

    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def create(self, validated_data):
        # Address模型类中有user属性,将user对象添加到模型类的创建参数中
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)

class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """
    class Meta:
        model = Address
        fields = ('title',)